package com.xiaohudie.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author xiao hu die
 * @Date 2022/3/15 15:24
 * @Version 1.0
 */
public class MyBatisUtil {
 private static SqlSessionFactory sqlSessionFactory = null ;
 private static SqlSession sqlSession =null;
 static {
  String config ="mybatis.xml";
  try {
   InputStream resourceAsStream = Resources.getResourceAsStream(config);
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 /**得到sqlSession*/
 public static SqlSession getConnection() {
  if (sqlSessionFactory != null) {
   sqlSession = sqlSessionFactory.openSession(true);
   return sqlSession;
  }else {
   System.out.println("连接数据库失败");
  }
  return null;
 }
 /**关闭sqlSession*/
 public static void close(){
  sqlSession.close();
 }
}
